<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>打卡记录 - 考勤管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
            padding: 30px;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #667eea;
        }
        
        .header h1 {
            color: #667eea;
            font-size: 28px;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            text-decoration: none;
            cursor: pointer;
            transition: background 0.3s;
        }
        
        .back-btn:hover {
            background: #5a6268;
        }
        
        .toolbar {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .filter-row {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr auto auto;
            gap: 15px;
            align-items: end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-group label {
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
            font-size: 14px;
        }
        
        .form-group input, .form-group select {
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }
        
        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #667eea;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s;
            font-weight: bold;
            white-space: nowrap;
        }
        
        .btn-primary {
            background: #667eea;
            color: white;
        }
        
        .btn-primary:hover {
            background: #5568d3;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn-success:hover {
            background: #218838;
        }
        
        .btn-danger {
            background: #dc3545;
            color: white;
        }
        
        .btn-danger:hover {
            background: #c82333;
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #5a6268;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        
        table thead {
            background: #667eea;
            color: white;
        }
        
        table th, table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
            font-size: 14px;
        }
        
        table tbody tr:hover {
            background: #f8f9fa;
        }
        
        .badge {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .badge-in {
            background: #d4edda;
            color: #155724;
        }
        
        .badge-out {
            background: #fff3cd;
            color: #856404;
        }
        
        .badge-device {
            background: #d1ecf1;
            color: #0c5460;
        }
        
        .badge-manual {
            background: #f8d7da;
            color: #721c24;
        }
        
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
        }
        
        .modal.show {
            display: flex;
        }
        
        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 15px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
        }
        
        .modal-header {
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid #667eea;
        }
        
        .modal-header h2 {
            color: #667eea;
            font-size: 22px;
        }
        
        .form-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }
        
        .message.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            display: block;
        }
        
        .message.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            display: block;
        }
        
        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
        }
        
        .empty {
            text-align: center;
            padding: 40px;
            color: #999;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }
        
        .stat-card h3 {
            font-size: 14px;
            margin-bottom: 10px;
            opacity: 0.9;
        }
        
        .stat-card .number {
            font-size: 32px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="user-bar">
            <span id="userInfo">👤 加载中...</span>
            <button class="logout-btn" onclick="logout()">🚪 退出</button>
        </div>
        
        <div class="header">
            <h1>⏰ 打卡记录管理</h1>
            <a href="index.html" class="back-btn">← 返回首页</a>
        </div>
        
        <div id="message" class="message"></div>
        
        <!-- 统计信息 -->
        <div class="stats">
            <div class="stat-card">
                <h3>总记录数</h3>
                <div class="number" id="totalCount">0</div>
            </div>
            <div class="stat-card">
                <h3>签入记录</h3>
                <div class="number" id="inCount">0</div>
            </div>
            <div class="stat-card">
                <h3>签出记录</h3>
                <div class="number" id="outCount">0</div>
            </div>
            <div class="stat-card">
                <h3>手工补计</h3>
                <div class="number" id="manualCount">0</div>
            </div>
        </div>
        
        <!-- 查询工具栏 -->
        <div class="toolbar">
            <div class="filter-row">
                <div class="form-group">
                    <label for="employeeId">员工</label>
                    <select id="employeeId">
                        <option value="">全部员工</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="fromDate">开始日期</label>
                    <input type="date" id="fromDate">
                </div>
                <div class="form-group">
                    <label for="toDate">结束日期</label>
                    <input type="date" id="toDate">
                </div>
                <button class="btn btn-primary" onclick="loadRecords()">🔍 查询</button>
                <button class="btn btn-success" onclick="showAddModal()">➕ 手工补计</button>
                <button class="btn btn-warning" onclick="showImportModal()" style="background: #17a2b8; color: white;">📁 CSV导入</button>
            </div>
        </div>
        
        <div id="tableContainer">
            <div class="loading">加载中...</div>
        </div>
    </div>
    
    <!-- CSV导入模态框 -->
    <div id="importModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>批量导入打卡记录</h2>
            </div>
            <div style="margin-bottom: 20px; padding: 15px; background: #e7f3ff; border-radius: 5px; font-size: 14px;">
                <strong>📋 CSV格式说明：</strong><br>
                每行一条记录，格式：<code>员工工号,打卡时间,类型,来源,备注</code><br>
                <strong>示例：</strong><br>
                <code>E1001,2025-10-28 09:00:00,IN,DEVICE,正常打卡</code><br>
                <code>E1001,2025-10-28 18:00:00,OUT,DEVICE,正常打卡</code><br>
                <br>
                <strong>说明：</strong><br>
                - 类型：IN（签入）或 OUT（签出）<br>
                - 来源：DEVICE（设备）或 MANUAL（手工）<br>
                - 备注可省略
            </div>
            <form id="importForm">
                <div class="form-group">
                    <label for="csvData">CSV数据 <span style="color: red;">*</span></label>
                    <textarea id="csvData" rows="10" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px; font-family: monospace;" placeholder="粘贴CSV数据..."></textarea>
                </div>
                <div class="form-group">
                    <label>或选择CSV文件</label>
                    <input type="file" id="csvFile" accept=".csv,.txt" style="width: 100%; padding: 10px;">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeImportModal()">取消</button>
                    <button type="submit" class="btn btn-success">开始导入</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 新增打卡记录模态框 -->
    <div id="recordModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>手工补计打卡</h2>
            </div>
            <form id="recordForm">
                <div class="form-group">
                    <label for="modalEmployeeId">员工 <span style="color: red;">*</span></label>
                    <select id="modalEmployeeId" required>
                        <option value="">请选择员工</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="eventTime">打卡时间 <span style="color: red;">*</span></label>
                    <input type="datetime-local" id="eventTime" required>
                </div>
                <div class="form-group">
                    <label for="eventType">类型 <span style="color: red;">*</span></label>
                    <select id="eventType" required>
                        <option value="IN">签入(IN)</option>
                        <option value="OUT">签出(OUT)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="source">来源</label>
                    <select id="source">
                        <option value="MANUAL">手工补计</option>
                        <option value="DEVICE">设备打卡</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="remark">备注</label>
                    <input type="text" id="remark" placeholder="例如：门禁故障补录">
                </div>
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-success">保存</button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        let records = [];
        let employees = [];
        
        // 页面加载时初始化
        window.addEventListener('load', () => {
            loadEmployees();
            setDefaultDates();
            loadRecords();
        });
        
        // 设置默认日期（当月）
        function setDefaultDates() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
            const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
            
            document.getElementById('fromDate').value = formatDate(firstDay);
            document.getElementById('toDate').value = formatDate(lastDay);
        }
        
        // 格式化日期为 YYYY-MM-DD
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        
        // 加载员工列表
        async function loadEmployees() {
            try {
                const response = await fetch('/api/employees');
                const result = await response.json();
                
                if (result.code === 200) {
                    employees = result.data;
                    
                    // 填充员工下拉框
                    const empSelect = document.getElementById('employeeId');
                    const modalEmpSelect = document.getElementById('modalEmployeeId');
                    
                    employees.forEach(emp => {
                        const option1 = new Option(`${emp.empNo} - ${emp.name}`, emp.id);
                        const option2 = new Option(`${emp.empNo} - ${emp.name}`, emp.id);
                        empSelect.add(option1);
                        modalEmpSelect.add(option2);
                    });
                }
            } catch (error) {
                console.error('加载员工列表失败:', error);
            }
        }
        
        // 加载打卡记录
        async function loadRecords() {
            const empId = document.getElementById('employeeId').value;
            const from = document.getElementById('fromDate').value;
            const to = document.getElementById('toDate').value;
            
            let url = '/api/clock-records?';
            if (empId) url += `empId=${empId}&`;
            if (from) url += `from=${from}&`;
            if (to) url += `to=${to}&`;
            
            try {
                const response = await fetch(url);
                const result = await response.json();
                
                if (result.code === 200) {
                    records = result.data;
                    updateStats();
                    renderTable();
                } else {
                    showMessage('加载失败: ' + result.message, 'error');
                }
            } catch (error) {
                showMessage('网络错误: ' + error.message, 'error');
            }
        }
        
        // 更新统计信息
        function updateStats() {
            const totalCount = records.length;
            const inCount = records.filter(r => r.eventType === 'IN').length;
            const outCount = records.filter(r => r.eventType === 'OUT').length;
            const manualCount = records.filter(r => r.source === 'MANUAL').length;
            
            document.getElementById('totalCount').textContent = totalCount;
            document.getElementById('inCount').textContent = inCount;
            document.getElementById('outCount').textContent = outCount;
            document.getElementById('manualCount').textContent = manualCount;
        }
        
        // 渲染表格
        function renderTable() {
            const container = document.getElementById('tableContainer');
            
            if (records.length === 0) {
                container.innerHTML = '<div class="empty">暂无打卡记录</div>';
                return;
            }
            
            let html = `
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>工号</th>
                            <th>姓名</th>
                            <th>打卡时间</th>
                            <th>类型</th>
                            <th>来源</th>
                            <th>备注</th>
                            <th>记录时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            records.forEach(record => {
                const typeClass = record.eventType === 'IN' ? 'badge-in' : 'badge-out';
                const typeText = record.eventType === 'IN' ? '签入' : '签出';
                const sourceClass = record.source === 'DEVICE' ? 'badge-device' : 'badge-manual';
                const sourceText = record.source === 'DEVICE' ? '设备' : '手工';
                
                html += `
                    <tr>
                        <td>${record.id}</td>
                        <td><strong>${record.empNo || '-'}</strong></td>
                        <td>${record.employeeName || '-'}</td>
                        <td>${record.eventTime || '-'}</td>
                        <td><span class="badge ${typeClass}">${typeText}</span></td>
                        <td><span class="badge ${sourceClass}">${sourceText}</span></td>
                        <td>${record.remark || '-'}</td>
                        <td>${record.createdAt || '-'}</td>
                        <td>
                            <button class="btn btn-danger" style="padding: 5px 10px; font-size: 12px;" onclick="deleteRecord(${record.id})">删除</button>
                        </td>
                    </tr>
                `;
            });
            
            html += '</tbody></table>';
            container.innerHTML = html;
        }
        
        // 显示新增模态框
        function showAddModal() {
            document.getElementById('recordForm').reset();
            
            // 设置默认时间为当前时间
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hour = String(now.getHours()).padStart(2, '0');
            const minute = String(now.getMinutes()).padStart(2, '0');
            document.getElementById('eventTime').value = `${year}-${month}-${day}T${hour}:${minute}`;
            
            document.getElementById('recordModal').classList.add('show');
        }
        
        // 关闭模态框
        function closeModal() {
            document.getElementById('recordModal').classList.remove('show');
            document.getElementById('recordForm').reset();
        }
        
        // 表单提交
        document.getElementById('recordForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const eventTimeValue = document.getElementById('eventTime').value;
            const formattedTime = eventTimeValue.replace('T', ' ') + ':00';
            
            const recordData = {
                employeeId: parseInt(document.getElementById('modalEmployeeId').value),
                eventTime: formattedTime,
                eventType: document.getElementById('eventType').value,
                source: document.getElementById('source').value,
                remark: document.getElementById('remark').value || null
            };
            
            try {
                const response = await fetch('/api/clock-records', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(recordData)
                });
                
                const result = await response.json();
                
                if (result.code === 201) {
                    showMessage('打卡记录创建成功', 'success');
                    closeModal();
                    loadRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'error');
            }
        });
        
        // 删除记录
        async function deleteRecord(id) {
            if (!confirm('确定要删除该打卡记录吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/clock-records/${id}`, {
                    method: 'DELETE'
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage('删除成功', 'success');
                    loadRecords();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('删除失败: ' + error.message, 'error');
            }
        }
        
        // 显示消息
        function showMessage(text, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = text;
            messageDiv.className = 'message ' + type;
            
            setTimeout(() => {
                messageDiv.className = 'message';
            }, 3000);
        }
        
        // 显示导入模态框
        function showImportModal() {
            document.getElementById('importForm').reset();
            document.getElementById('importModal').classList.add('show');
        }
        
        // 关闭导入模态框
        function closeImportModal() {
            document.getElementById('importModal').classList.remove('show');
        }
        
        // CSV文件选择
        document.getElementById('csvFile').addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    document.getElementById('csvData').value = event.target.result;
                };
                reader.readAsText(file, 'UTF-8');
            }
        });
        
        // 导入表单提交
        document.getElementById('importForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const csvData = document.getElementById('csvData').value.trim();
            if (!csvData) {
                showMessage('请输入或选择CSV数据', 'error');
                return;
            }
            
            try {
                const response = await fetch('/api/clock-records/import', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ csvData: csvData })
                });
                
                const result = await response.json();
                
                if (result.code === 200) {
                    showMessage(result.message, 'success');
                    closeImportModal();
                    loadRecords();
                    updateStats();
                } else {
                    showMessage(result.message, 'error');
                }
            } catch (error) {
                showMessage('导入失败: ' + error.message, 'error');
            }
        });
        
        // 点击模态框外部关闭
        document.getElementById('recordModal').addEventListener('click', (e) => {
            if (e.target.id === 'recordModal') {
                closeModal();
            }
        });
        
        document.getElementById('importModal').addEventListener('click', (e) => {
            if (e.target.id === 'importModal') {
                closeImportModal();
            }
        });
    </script>
</body>
</html>

